#!/usr/bin/perl -wc

package RFCMail::DNS::BlockList::Target;

use strict;
use Carp qw(croak);
use RFCMail::DNS::BlockList::Query;


sub new_rhs {
    my ($class, $rhs) = @_;
    return (bless [ $rhs, {} ], $class);
}


sub new_ip {
    my ($class, $ip) = @_;
    $ip =~ /\A(\d+)\.(\d+)\.(\d+)\.(\d+)\z/
	or croak("$ip is not an IPv4 address");
    return ($class->new_rhs("$4.$3.$2.$1"));
}


sub results {
    my $self = shift;
    my $cache = $self->[1];
    return (values %$cache)
	if not @_;
    my @slice = $self->enlist(@_);
    return (@$cache{@slice})
}


sub hits {
    my $self = shift;
    my @hits;
    for ($self->enlist(@_)) {
	push @hits, $_
	    if $self->[1]->{$_}->a_records;
    }
    return (@hits);
}


sub summary {
    my $self = shift;
    my @summary;
    for ($self->enlist(@_)) {
	push @summary, "$_:", map("  $_", $self->[1]->{$_}->summary);
    }
    @summary = ("No blocklists have been queried.")
	if not @summary;
    return (@summary);
}


sub enlist {
    my ($self, @list) = @_;
    if (@list) { $self->query(@list) }
    else { @list = keys %{$self->[1]} }
    return (@list);
}


sub query {
    my ($target, $cache) = @{shift()};
    for (@_) {
	$cache->{$_} = RFCMail::DNS::BlockList::Query->new("$target.$_")
	    if not exists($cache->{$_});
    }
}


1;
